#!/bin/bash

##
# Copyright 2012 Rob van de Werken
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##

IFS=$'\012' # set only newline as seperator
SITE="http://gids.publiekeomroep.nl"
##read channels from file
CHANNELSFILE="channels.lst"
OUTPUTSQL="tvgids.sql"
OUTPUTXML="tvgids.xml"

if [ -f "$CHANNELSFILE" ]; then
	CHANNELS="$(grep "^[[:digit:]]\+=.*" $CHANNELSFILE)"
else
	echo "Channelsfile '$CHANNELSFILE'is missing."
	read -p "Do you want to generate it [Y/n]? " -n 1 ANSWER
	echo
	if [ "$ANSWER" == "Y" ] || [ "$ANSWER" == "y" ]; then
		echo "## Lines starting with a # will be ignored" > $CHANNELSFILE
		echo "## Order the lines according to your preference" >> $CHANNELSFILE

		wget -O - "http://gids.publiekeomroep.nl/home/" \
		| grep "<option value=\"[0-9]\+\">" \
		| grep -v "Ga naar een zender" \
		| sed -n "s/.*<option value=\"\([0-9]\+\)\">\(.*\)<\/option>/\1=\2/p" \
		>> $CHANNELSFILE

		echo
		echo "Manually change $CHANNELSFILE for personal preference."
	fi
	exit
fi

##Array for all categories
CATARR[1]="Jeugd"
CATARR[2]="Animatie"
CATARR[3]="Educatief"
CATARR[4]="Informatief"
CATARR[5]="Muziek"
CATARR[6]="Sport"
CATARR[7]="Film"
CATARR[8]="Amusement"
CATARR[10]="Serie/Soap"
CATARR[11]="Comedy"
CATARR[12]="Nieuws"
CATARR[13]="Overige"
CATARR[15]="Misdaad"
CATARR[17]="Documentaire"
CATARR[18]="Kunst/Cultuur"

## SQL header
echo "BEGIN TRANSACTION;" > $OUTPUTSQL
#echo "create table programme (id INTEGER PRIMARY KEY, start DATE, stop DATE, channel VARCHAR(15), category VARCHAR(15), title TEXT, description TEXT);" >> $OUTPUTSQL
echo "drop table if exists channels;" >> $OUTPUTSQL
echo "create table channels (sort INTEGER PRIMARY KEY, id INTEGER , name VARCHAR(15));" >> $OUTPUTSQL
echo "drop table if exists programme;" >> $OUTPUTSQL
echo "create table programme (id INTEGER PRIMARY KEY, start INTEGER, stop INTEGER, channel INTEGER, category VARCHAR(15), title TEXT, description TEXT);" >> $OUTPUTSQL
## XML header
echo "<?xml version=\"1.0\" encoding=\"ISO-8859-15\"?>" > $OUTPUTXML
echo "<!DOCTYPE tv SYSTEM \"xmltv.dtd\">" >> $OUTPUTXML
echo >> $OUTPUTXML
echo "<tv source-info-url=\"$SITE\" source-info-name=\"Publieke Omroep\" generator-info-name=\"xmltv-grabber-nl 1\" generator-info-url=\"http://www.xmltv.org/\">" >> $OUTPUTXML

## Add channels to files
for line in $CHANNELS; do
	## Add channel to SQL
	echo "INSERT INTO channels VALUES(NULL,${line%%=*},\"${line##*=}\");" >> $OUTPUTSQL
	## Add channel to XML
	echo "  <channel id=\"${line%%=*}\">" >> $OUTPUTXML
	echo "    <display-name lang=\"nl\">${line##*=}</display-name>" >> $OUTPUTXML
	echo "  </channel>" >> $OUTPUTXML
done
echo >> $OUTPUTXML

## Line for yesterday
#"$SITE/overzicht/zender/${line%%=*}/$(date -d "-1 day" "+%Y/%m/%d")/?actueel=0&allezenders=0&col=tijd&order=ASC" \

## The actual grabber
for line in $CHANNELS; do
	for CSVline in $(wget -q -O - \
			"$SITE/overzicht/zender/${line%%=*}/$(date "+%Y/%m/%d")/?actueel=0&allezenders=0&col=tijd&order=ASC" \
			"$SITE/overzicht/zender/${line%%=*}/$(date -d "+1 day" "+%Y/%m/%d")/?actueel=0&allezenders=0&col=tijd&order=ASC" \
			"$SITE/overzicht/zender/${line%%=*}/$(date -d "+2 day" "+%Y/%m/%d")/?actueel=0&allezenders=0&col=tijd&order=ASC" \
		| grep 'Gids.addUitzending' \
		| grep -v "'Z@pp'\|'Z@ppelin'\|'RTL Telekids'\|'Disney XD'\|'Teleshop 5'\|'Nederland 3'\|'KRO Kindertijd'" \
		| sed -n "s/.*Gids.addUitzending([0-9]\+, new Uitzending(\(.*\)));/\1,$1/p")
	do
		CHANID=${line%%=*}
		#CHAN=${line##*=}
		## Parse front section
		RESULT=${CSVline#*,*, \'}
		BEGIN=${RESULT%%\',*}
		RESULT=${RESULT#*, \'}
		STAMP=${RESULT%%\',*}
		RESULT=${RESULT#*, \'}
		END=${RESULT%%\',*}
		RESULT=${RESULT#*, \'}
		
		## Parse rear section
		#CHAN=${RESULT##*,}
		RESULT=${RESULT%,*,*,*,*,*,*}
		CAT=${CATARR[${RESULT##*, }]}
		RESULT=${RESULT%\',*,*}
		
		## Parse remainder and replace \' with '
		TITLE=${RESULT%\',*}
		TITLE=${TITLE/\\\'/\'}
		DESC=${RESULT#*, \'}
		DESC=${DESC/\\\'/\'}
		
		## Calculate duration
		BEGIN1=${BEGIN:0:2}
		BEGIN2=${BEGIN:3}
		END1=${END:0:2}
		END2=${END:3}
		BEGIN1=${BEGIN1#0}
		BEGIN2=${BEGIN2#0}
		END1=${END1#0}
		END2=${END2#0}
		DIFF=$(( ((($END1-$BEGIN1) * 60) + $END2 - $BEGIN2 ) * 60 ))
		if [ $DIFF -lt 0 ]; then
			DIFF=$(( $DIFF + 86400 ))
		fi
		
		## SQL result
		echo "INSERT into programme VALUES (NULL, $STAMP, $(( $DIFF + $STAMP )), \"$CHANID\", \"$TITLE\", \"$DESC\", \"$CAT\");" >> $OUTPUTSQL
		## XML result
		echo "  <programme start='`date -d @$STAMP +%Y%m%d%H%M%S` +0200' stop='`date -d @$(( $DIFF + $STAMP )) +%Y%m%d%H%M%S` +0200' channel='$CHANID'>" >> $OUTPUTXML
		echo "    <title>$TITLE</title>" >> $OUTPUTXML
		echo "    <desc>$DESC</desc>" >> $OUTPUTXML
		echo "    <category>$CAT</category>" >> $OUTPUTXML
		echo "  </programme>" >> $OUTPUTXML

	done
done
## SQL footer
echo "COMMIT;" >> $OUTPUTSQL
## XML footer
echo "</tv>" >> $OUTPUTXML

## Create database:
if [ -n "`which sqlite3`" ]; then
	rm -f tvgids.db
	cat tvgids.sql | sqlite3 tvgids.db
fi
## Compress sql
if [ -n "`which gzip`" ]; then
	rm -f tvgids.sql.gz
	gzip -9 tvgids.sql
fi

unset IFS
